package edu.ntu.cloudroid.xacml.function;

import java.util.List;


import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.sun.xacml.EvaluationCtx;
import com.sun.xacml.attr.AttributeValue;
import com.sun.xacml.attr.BooleanAttribute;
import com.sun.xacml.attr.StringAttribute;
import com.sun.xacml.cond.EvaluationResult;
import com.sun.xacml.cond.FunctionBase;

import edu.ntu.cloudroid.model.friend.GroupData;
import edu.ntu.cloudroid.model.friend.GroupInfo;
import edu.ntu.cloudroid.model.profile.ProfileData;
import edu.ntu.cloudroid.server.backendservice.GroupService;
import edu.ntu.cloudroid.server.backendservice.ProfileService;
import edu.ntu.cloudroid.xacml.Utilities;
import edu.ntu.cloudroid.xacml.XACMLStrings;
import edu.ntu.cloudroid.xacml.cache.DataService;

public class GroupContainsKey extends FunctionBase
{
   // the parameter types, in order, and whether or not they're bags
   private static final String params[] = { StringAttribute.identifier};
   private static final boolean bagParams[] = { false};

   public GroupContainsKey()
   {
      // use the constructor that handles mixed argument types
      super(XACMLStrings.FN_GroupContainsKey, 0, params, bagParams,
            BooleanAttribute.identifier, false);
   }

   @SuppressWarnings("rawtypes")
   @Override
   public EvaluationResult evaluate(List inputs, EvaluationCtx context)
   {
      AttributeValue[] argValues = new AttributeValue[inputs.size()];
      EvaluationResult result = evalArgs(inputs, context, argValues);
      if (result != null)
         return result;

      // cast the resolved values into specific types
      String groupNameString = ((StringAttribute) (argValues[0])).getValue();     
           
      ProfileData resource=null, subject=null;
      try{
    	  subject = ProfileService.getProfile(Utilities.getSubjectPersonKey(context));    	  
    	  resource = ProfileService.getProfile(Utilities.getResourcePersonKey(context));       
      }
      catch (Exception e){};
      
      List<GroupData> groups = GroupService.getGroupData(resource.getEmailAddress(), subject.getEmailAddress());
      boolean evalResult = false;
      for (GroupData g: groups){
    	if (g.getGroupName().equals(groupNameString)){
    		evalResult = true;
    		break;
    	}
      }      	
      return EvaluationResult.getInstance(evalResult);
   }
}
